using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using ThaiLanguageTools.DataStruct;

namespace ThaiLanguageTools.SrcParse
{
    class TeddySqlParser : DictParser
    {
        protected override XDictHeader GetHeader()
        {
            return new XDictHeader(
                "Teddy",
                @"http://developer.novell.com/wiki/index.php/Teddy_(Thai_English_DictionarY)",
                "GPL license");
        }

        protected override XDictEntry ParseEntry(StreamReader sr)
        {
            const String wordStart = "insert into wikidata values ( ";
            const String modeTrans = "=== Translations ===";
            const String modeSynonyms = "=== Synonyms ===";
            const String modeAntonyms = "=== Antonyms ===";
            const String modeDefinitions = "=== Definitions ===";

            XDictEntry entry = null;
            List<XWordInfo> mode = null;

            while (true)
            {
                String line = sr.ReadLine();
                if (line == null) { return null; } // EOF

                if (line == "' );") { return entry; }
                else if (line.StartsWith(wordStart))
                {
                    line = line.Substring(wordStart.Length);
                    String[] parts = line.Split(',');

                    String text = parts[0].Trim(' ', '\'');
                    String pos = parts[1].Trim(' ', '\'');
                    if (pos == "n/a") { pos = null; }
                    String language = DetectLanguage(text);

                    entry = new XDictEntry(new XWordInfo(text, language, pos));
                }
                else if (line.StartsWith("=== "))
                {
                    Debug.Assert(entry != null);
                    if (line == modeTrans) { mode = entry.Translations; }
                    else if (line == modeSynonyms) { mode = entry.Synonyms; }
                    else if (line == modeAntonyms) { mode = entry.Antonyms; }
                    else if (line == modeDefinitions) { mode = entry.Definitions; }
                    else
                    {
                        Debug.Assert(false, "Unknown mode: " + line);
                    }
                }
                else if (!String.IsNullOrEmpty(line))
                {
                    String text = line.Trim('*', '#', ' ', '[', ']');
                    String language = DetectLanguage(text);
                    XWordInfo word = new XWordInfo(text, language);

                    mode.Add(word);
                }
            }
        }
    }
}
